package asia.doing.service.manage;

import asia.doing.entity.ArticleTag;
import asia.doing.entity.Tag;
import asia.doing.mapper.TagMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

@Service(value = "manageTagService")
public class TagService {
    @Resource
    private TagMapper tagMapper;

    public List<Tag> selectTag(Tag tag) {
        List<Tag> tags = tagMapper.selectAll(tag);
        for (Tag tag1 : tags) {
            Integer id1 = tag1.getId();
            ArticleTag articleTag = new ArticleTag();
            articleTag.setTagId(id1);
            List<ArticleTag> articleIds = tagMapper.selectByArtOrTagId(articleTag);
            //声明一个Set列表
            HashSet<Integer> articleIdSets = new HashSet<>();
            for (ArticleTag articleTag1 : articleIds) {
                articleIdSets.add(articleTag1.getArticleId());
            }
            Integer[] articleIdsArray = articleIdSets.toArray(new Integer[articleIdSets.size()]);
            tag1.setArticles(articleIdsArray);
        }
        return tags;
    }

    public void addTag(Tag tag) {
        tagMapper.insert(tag);
    }

    public void updateTag(Tag tag) {
        tagMapper.updateById(tag);
    }

    public void deleteTag(Integer id) {
        tagMapper.deleteById(id);
        tagMapper.deleteByTagId(id);
    }

    public PageInfo<Tag> selectPage(Tag tag, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //注意:这里获取到的信息是重复的
        List<Tag> tags = tagMapper.selectAll(tag);
        for (Tag tag1 : tags) {
            Integer id1 = tag1.getId();
            ArticleTag articleTag = new ArticleTag();
            articleTag.setTagId(id1);
            List<ArticleTag> articleIds = tagMapper.selectByArtOrTagId(articleTag);
            //声明一个Set列表
            HashSet<Integer> articleIdSets = new HashSet<>();
            for (ArticleTag articleTag1 : articleIds) {
                articleIdSets.add(articleTag1.getArticleId());
            }
            Integer[] articleIdsArray = articleIdSets.toArray(new Integer[articleIdSets.size()]);
            tag1.setArticles(articleIdsArray);
        }
        PageInfo<Tag> pageInfo = PageInfo.of(tags);
        return pageInfo;
    }
}
